package com.sy.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.constant.JwtClaimsConstant;
import com.sy.context.BaseContext;
import com.sy.dto.EmployeeDTO;
import com.sy.dto.EmployeeLoginDTO;
import com.sy.dto.EmployeePageQueryDTO;
import com.sy.pojo.Employee;
import com.sy.properties.JwtProperties;
import com.sy.result.PageResult;
import com.sy.result.Result;
import com.sy.service.EmployeeService;
import com.sy.utils.JwtUtil;
import com.sy.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@Api(tags = "员工相关接口")
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;



    /**
     * 登录
     * @param employeeLoginDTO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .username(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        //打印请求数据日志
        log.info("员工退出系统成功...");
        return Result.success();
    }


    @ApiOperation("员工分页查询")
    @GetMapping("/findAll")
    public Result<PageResult> findAll(EmployeePageQueryDTO employeePageQueryDTO) {
        //打印请求数据日志
        log.info("员工分页查询：{}", employeePageQueryDTO);
        //调用业务层实现
        PageResult pageResult=employeeService.findAll(employeePageQueryDTO);

        return Result.success(pageResult);
    }

    @GetMapping("/doExistUsername")
    @ApiOperation("查询用户名是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的用户名",name = "username",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistUsername(String username){
        //打印请求数据日志
        log.info("用户名为：{}",username);
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        Employee employee = employeeService.getOne(queryWrapper);
        if(employee==null){
            return Result.success();
        }else {
            return Result.error("用户名已经存在");
        }
    }

    @GetMapping("/doExistPhone")
    @ApiOperation("查询手机号是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的手机号" ,name = "phone",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistPhone(String phone){
        //打印请求数据日志
        log.info("手机号为：{}",phone);
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getPhone,phone);
        Employee employee = employeeService.getOne(queryWrapper);
        if(employee==null){
            return Result.success();
        }else {
            return Result.error("手机号已经存在");
        }
    }

    @PostMapping("/save")
    @ApiOperation("新增员工信息")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        //打印请求数据日志
        try {
            long id = Thread.currentThread().getId();
            log.info("线程id：{}",id);
            log.info("新增员工：{}",employeeDTO);
            employeeService.saveEmp(employeeDTO);
        } catch (Exception e) {
            throw new RuntimeException("新增员工失败");
        }
        return Result.success();
    }

    @PostMapping("/update")
    @ApiOperation("修改员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        //打印请求数据日志
        try {
            log.info("修改员工信息：{}",employeeDTO);
            //处理下 客户端传递的数据封装到EmployeeDTO 复制 给employee对象
            Employee employee=new Employee();
            BeanUtils.copyProperties(employeeDTO,employee);
            //employee就已经存在了 真实姓名 手机号 性别 员工状态
            //修改时间
            employee.setUpdateTime(LocalDateTime.now());
            //设置修改人
            employee.setUpdateUser(BaseContext.getCurrentId());
            //修改员工信息
            employeeService.updateById(employee);
        } catch (Exception e) {
            throw new RuntimeException("修改员工失败");
        }
        return Result.success();
    }
    @PostMapping("/delete")
    @ApiOperation("删除员工")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "是一个list集合",name = "ids",
                    required = true,
                    dataTypeClass = List.class)
    })
    public Result<String> delete(@RequestBody List<Long> ids){
        try {
            //打印请求数据日志
            log.info("用户名为：{}",ids);
            //1.获取当前员工信息的id
            Long currentId = BaseContext.getCurrentId();
            //2.实现删除
            //判断当前员工的id在ids中是否包含(存在)，如果存在不能删除
            if(ids.contains(currentId)){
                return Result.error("不可以删除当前登录用户");
            }else {
                //如果不存在进行逻辑删除(修改)
                LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Employee::getId,ids);

                Employee employee=new Employee();
                employee.setIsDelete(0);
                employee.setUpdateTime(LocalDateTime.now());
    //            employee.setUpdateUser(BaseContext.getCurrentId());
                //实现逻辑删除
                employeeService.update(employee,queryWrapper);
                return Result.success();
            }
        } catch (Exception e) {
            throw new RuntimeException("删除失败");
        }
    }

    @GetMapping("/getEmpByPassword")
    @ApiOperation("校验密码原是否正确")
    @ApiImplicitParams(@ApiImplicitParam(value = "当前登录员工的密码",name = "password",required = true,dataTypeClass = String.class))
    public Result getEmpByPassword(String password){
        //打印请求数据日志
        log.info("校验密码原是否正确：{}",password);
        //获取当前用户输入的登录密码， 通过md5进行加密
        String MD5password= DigestUtils.md5DigestAsHex(password.getBytes());
        //获取当前登录用户保存在数据库的密码
        Long empId=BaseContext.getCurrentId();
        //根据员工id查询数据库
        Employee employee=employeeService.getById(empId);
        //判断输入的密码和从数据库查询的密码 是否一致
        if(employee.getPassword().equals(MD5password)){
            return Result.success();
        }else {
            return Result.error("密码输入错误");
        }
    }

    @PostMapping("/updatePassword")
    @ApiOperation("校验密码原是否正确")
    @ApiImplicitParams(@ApiImplicitParam(value = "员工的新密码",name = "password",required = true,dataTypeClass = String.class))
    public Result updatePassword(String password){
        //打印请求数据日志
        log.info("校验密码原是否正确：{}",password);
        try {
            //获取当前用户输入的登录密码， 通过md5进行加密
            String MD5password= DigestUtils.md5DigestAsHex(password.getBytes());
            //获取当前登录用户保存在数据库的密码
            Long empId=BaseContext.getCurrentId();
            //创建员工对象
            Employee employee=new Employee();
            employee.setId(empId);
            employee.setPassword(MD5password);
            //修改操作
            employeeService.updateById(employee);
            return Result.success();
        } catch (Exception e) {
            throw new RuntimeException("密码错误...");
        }

    }
}
